<template>
  <div class="residency-application">
    <h1>桂林电子科技大学科技园众创空间</h1>
    <h2>入驻申请书(教师)</h2>
    <div v-if="form.status !== undefined" class="status-display">
      <el-tag :type="getStatusType(form.status)" size="large" effect="dark">
        {{ getStatusText(form.status) }}
      </el-tag>
    </div>
    <el-form :model="form" :rules="rules" label-width="150px" ref="formRef" style="max-width: 1200px; width: 100%" :disabled="form.status !== undefined && form.status !== 0">
      <!-- 基本信息 -->
      <el-card>
        <div slot="header" class="header">基本信息</div>
        <el-form-item label="团队/公司名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入团队或公司的名称" />
        </el-form-item>
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="申请日期" prop="applyDate">
              <el-date-picker v-model="form.applyDate" type="date" placeholder="点击选择日期" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="团队/公司人数" prop="numbers">
              <el-input-number v-model="form.numbers" :min="1" placeholder="请输入团队人数" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="项目名称" prop="itemName">
              <el-input v-model="form.itemName" placeholder="请输入项目的名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="公司注册时间" prop="registerDate">
              <el-date-picker v-model="form.registerDate" type="date" placeholder="点击选择日期" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司组织机构代码" prop="organizationCode">
              <el-input v-model="form.organizationCode" placeholder="请输入公司组织机构代码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="所属行业" prop="industry">
          <el-select v-model="form.industry" placeholder="请选择所属行业">
            <el-option label="信息技术" value="信息技术" />
            <el-option label="智能制造" value="智能制造" />
            <el-option label="生物医药" value="生物医药" />
            <el-option label="文化创意" value="文化创意" />
            <el-option label="电子商务" value="电子商务" />
            <el-option label="其他" value="其他" />
          </el-select>
          <el-input
              v-if="form.industry === '其他'"
              v-model="form.otherIndustry"
              placeholder="请输入其他行业"
              style="margin-left: 10px; width: 200px"
          />
        </el-form-item>
      </el-card>

      <!-- 联系人信息 -->
      <el-card>
        <div slot="header" class="header">联系人信息</div>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactName">
              <el-input v-model="form.contactName" placeholder="请输入联系人的姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="contactPhone">
              <el-input v-model="form.contactPhone" placeholder="请输入联系人的电话号码" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 公司信息 -->
      <el-card>
        <div slot="header" class="header">公司信息</div>
        <el-form-item label="公司注册资金" prop="registerMoney">
          <div class="input-with-unit">
            <el-input-number
                v-model="form.registerMoney"
                :min="0"
                :max="1000000000"
                placeholder="请输入公司注册资金"
                style="width: calc(100% - 60px);"
            />
            <span style="margin-left: 10px;">元</span>
          </div>
        </el-form-item>

        <el-form-item label="项目/公司股权构成(%)" prop="shareholdingRatio">
          <el-input
              v-model="form.shareholdingRatio"
              type="textarea"
              placeholder="请详细描述项目或公司的股权分配情况"
          />
        </el-form-item>
        <el-form-item label="是否经学校人事处兼职情况备案" prop="isQualified">
          <el-radio-group v-model="form.isQualified">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="经营范围（产品/服务）" prop="businessScope">
          <el-input
              v-model="form.businessScope"
              type="textarea"
              placeholder="请简要说明公司的主要产品或服务"
          />
        </el-form-item>
      </el-card>

      <!-- 主要成员信息 -->
      <el-card>
        <div slot="header" class="header1">主要成员信息</div>
        <el-form-item label-width="0" prop="members">
          <el-button type="primary" @click="addMember">增加成员</el-button>
          <el-table :data="form.members" style="width: 100%">
            <el-table-column label="序号" type="index" width="50" />
            <el-table-column prop="name" label="姓名">
              <template #default="scope">
                <el-form-item :prop="'members.' + scope.$index + '.name'"
                  :rules="[{ required: true, message: '请输入姓名', trigger: 'blur' }]">
                  <el-input v-model="scope.row.name" placeholder="请输入成员姓名" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="department" label="学院/部门">
              <template #default="scope">
                <el-form-item :prop="'members.' + scope.$index + '.department'"
                  :rules="[{ required: true, message: '请输入所属学院或部门', trigger: 'blur' }]">
                  <el-input v-model="scope.row.department" placeholder="请输入所属学院或部门" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="major" label="专业方向">
              <template #default="scope">
                <el-form-item :prop="'members.' + scope.$index + '.major'"
                  :rules="[{ required: true, message: '请输入专业方向', trigger: 'blur' }]">
                  <el-input v-model="scope.row.major" placeholder="请输入专业方向" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="phone" label="手机号码">
              <template #default="scope">
                <el-form-item :prop="'members.' + scope.$index + '.phone'"
                  :rules="[{ required: true, message: '请输入手机号码', trigger: 'blur' },{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }]">
                  <el-input v-model="scope.row.phone" placeholder="请输入手机号码" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="qq" label="QQ号">
              <template #default="scope">
                <el-form-item :prop="'members.' + scope.$index + '.qq'"
                  :rules="[{ required: true, message: '请输入QQ号码', trigger: 'blur' },{ pattern: /^[1-9][0-9]{4,11}$/, message: '请输入正确的QQ号码', trigger: 'blur' }]">
                  <el-input v-model="scope.row.qq" placeholder="请输入QQ号码" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="job" label="公司/团队职务">
              <template #default="scope">
                <el-form-item :prop="'members.' + scope.$index + '.job'"
                  :rules="[{ required: true, message: '请输入在公司或团队中的职务', trigger: 'blur' }]">
                  <el-input v-model="scope.row.job" placeholder="请输入在公司或团队中的职务" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-button type="danger" @click="removeMember(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-card>

      <!-- 入驻及缴费信息 -->
      <el-card>
        <div slot="header" class="header">入驻及缴费信息</div>
        <el-form-item label="是否有实际入驻场地" prop="hasPhysicalSpace">
          <el-radio-group v-model="form.hasPhysicalSpace" @change="handleSpaceChange">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="卡座号" prop="seatNumber" v-if="form.hasPhysicalSpace">
          <el-input
              v-model="form.seatNumber"
              placeholder="请输入卡座号"
              style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="缴费类型" prop="paymentTypes">
          <el-checkbox-group v-model="form.paymentTypes">
            <el-checkbox label="保证金">保证金</el-checkbox>
            <el-checkbox label="卡座使用费">卡座使用费</el-checkbox>
            <el-checkbox label="管理费">管理费</el-checkbox>
            <el-checkbox label="其他费用">其他费用</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="缴费金额" prop="paymentAmount">
          <div class="input-with-unit">
            <el-input-number
                v-model="form.paymentAmount"
                :min="0"
                :precision="2"
                placeholder="请输入缴费金额"
                style="width: calc(100% - 60px);"
            />
            <span style="margin-left: 10px;">元</span>
          </div>
        </el-form-item>

      </el-card>

      <!-- 项目信息 -->
      <el-card>
        <div slot="header" class="header">项目信息</div>
        <el-form-item label="项目/公司简介（300字以内）" prop="projectIntroduction">
          <el-input
              v-model="form.projectIntroduction"
              type="textarea"
              placeholder="请用300字以内的文字介绍您的项目或公司"
          />
        </el-form-item>
        <el-form-item
            label="您想获得的帮助（如创业辅导、投融资服务、市场推广）"
            prop="helpDescription"
        >
          <el-input
              v-model="form.helpDescription"
              type="textarea"
              placeholder="请告诉我们您希望得到哪些帮助"
          />
        </el-form-item>
      </el-card>

      <!-- 文件上传 -->
      <el-card>
        <div slot="header" class="header">文件上传</div>
        <el-form-item label="身份证明材料" prop="certificate">
          <el-upload
              class="upload-demo"
              :auto-upload="false"
              :on-change="(file) => handleFileUpload(file, 'certificate')"
              :limit="1"
              :file-list="certificateList"
          >
            <template #trigger>
              <el-button type="primary">选择文件</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                请上传身份证、教师证复印件，支持jpg/png/pdf格式
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="项目相关文件" prop="projectfile">
          <el-upload
              class="upload-demo"
              :auto-upload="false"
              :on-change="(file) => handleFileUpload(file, 'projectfile')"
              :limit="5"
              :file-list="projectFileList"
              multiple
          >
            <template #trigger>
              <el-button type="primary">选择文件</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                请上传项目相关文件（如奖项、专利、图片等），支持jpg/png/pdf格式，最多5个文件
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="缴费回单" prop="paymentReceipt">
          <el-upload
              class="upload-demo"
              :auto-upload="false"
              :on-change="(file) => handleFileUpload(file, 'paymentReceipt')"
              :limit="1"
              :file-list="paymentReceiptList"
          >
            <template #trigger>
              <el-button type="primary">选择文件</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                请上传缴费回单，支持jpg/png/pdf格式
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-card>

      <!-- 承诺 -->
      <el-card>
        <div slot="header" class="header">承诺</div>
        <el-form-item class="promise-text">
          <p>
            本团队(公司)承诺上述内容属实，如有任何虚假与隐瞒,本团队(公司)愿承担一切法律责任和后果。
          </p>
          <p>承诺人: <el-input v-model="form.contactName" placeholder="请在此签名"></el-input></p>
          <p>
            日期: <el-date-picker v-model="form.applyDate" type="date" placeholder="请选择签署日期" />
          </p>
        </el-form-item>
      </el-card>

      <!-- 审批意见 -->
      <el-card>
        <div slot="header" class="header">审批意见</div>
        <el-form-item label="办公室主任意见">
          <el-input disabled type="textarea" placeholder="等待办公室主任填写意见" />
        </el-form-item>
        <el-form-item label="领导审批意见">
          <el-input disabled type="textarea" placeholder="等待领导填写审批意见" />
        </el-form-item>
      </el-card>

      <!-- 提交按钮 -->
      <el-form-item>
        <el-button v-if="form.status === 0" type="primary" @click="submitForm">提交</el-button>
        <el-button v-if="form.status === 0" @click="saveDraft">保存草稿</el-button>
        <el-button v-if="form.status === 0" @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
    <span>注：请同时提供团队成员身份证、学生证/教师证复印件及项目相关文件（如奖项、专利、图片等）。</span>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, nextTick, onMounted } from 'vue';
import {
  ElMessage,
  type UploadFile,
  type UploadFiles,
  type UploadInstance,
  type UploadProps,
} from 'element-plus';
import {
  residencyApplication,
  residencyApplicationList,
  zcresidencyApplication,
  getApplicationFromId, editApplication,
} from '@/api/enterpeise';
import { uploadFile } from '@/api/file';
import { useRouter } from 'vue-router';
import { reqFeedback } from '@/utils/reqFeedback';
import { getLoginUserId } from '@/utils/storage';
import type { ResidencyApplicationStudent } from '@/types/type';
import FileUpload from '../../components/fileUpload.vue';
import type { FormInstance, FormRules } from 'element-plus';
import type { AjaxResult } from '@/types/resultTypes';

// 定义props
interface Props {
  id?: string;
}

const props = withDefaults(defineProps<Props>(), {
  id: ''
});

const router = useRouter();
const formRef = ref<FormInstance>();

// 表单验证规则
const rules = reactive<FormRules>({
  name: [{ required: true, message: '请输入团队/公司名称', trigger: 'blur' }],
  applyDate: [{ required: true, message: '请选择申请日期', trigger: 'change' }],
  itemName: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
  numbers: [{ required: true, message: '请输入团队/公司人数', trigger: 'blur' }],
  contactName: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  contactPhone: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  industry: [{ required: true, message: '请选择所属行业', trigger: 'change' }],
  registerMoney: [{ required: true, message: '请输入公司注册资金', trigger: 'blur' }],
  ShareholdingRatio: [
    { required: true, message: '请输入项目/公司股权构成', trigger: 'blur' },
    { pattern: /^[\d%.,，]*\d+(\.\d+)?[\d%.,，]*$/, message: '只能包含数字、百分号、小数点和逗号，如：张三40%，李四60%', trigger: 'blur' }
  ],
  businessScope: [{ required: true, message: '请输入经营范围', trigger: 'blur' }],
  members: [{
    type: 'array',
    required: true,
    message: '请至少添加一个成员信息',
    trigger: 'change'
  }],
  projectIntroduction: [{ required: true, message: '请输入项目介绍', trigger: 'blur' }],
  helpDescription: [{ required: true, message: '请输入需要帮助描述', trigger: 'blur' }],
  hasPhysicalSpace: [{ required: true, message: '请选择是否有实际入驻场地', trigger: 'change' }],
  seatNumber: [{ required: true, message: '请输入卡座号', trigger: 'change' }],
  paymentTypes: [{ required: true, message: '请选择缴费类型', trigger: 'change' }],
  paymentAmount: [{ required: true, message: '请输入缴费金额', trigger: 'blur' }],
});

// 类型补充
interface ResidencyApplicationTeacherExt extends ResidencyApplicationStudent {
  status?: number;
  id?: number;
  type?: number;
  otherIndustry: string;
}

// 表单数据
const totalRecord = ref(0);
const form = reactive<ResidencyApplicationTeacherExt>({
  type: 1,
  name: '',
  applyDate: '',
  itemName: '',
  numbers: 0,
  contactName: '',
  contactPhone: '',
  registerDate: '',
  organizationCode: '',
  industry: '',
  otherIndustry: '',
  registerMoney: 0,
  shareholdingRatio: '',
  isQualified: false,
  businessScope: '',
  members: [
    {
      name: '',
      department: '',
      major: '',
      phone: '',
      qq: '',
      job: '',
    },
  ],
  hasPhysicalSpace: false,
  seatNumber: '',
  paymentTypes: [], // 用于前端多选框绑定
  paymentAmount: 0,
  projectIntroduction: '',
  helpDescription: '',
  teacherOpinion: '',
  collegeOpinion: '',
  officeOpinion: '',
  leaderOpinion: '',
  status: 0,
  id: undefined,
  paymentType: '', // 实际提交给后端的字段
});

// 加载现有数据
const loadExistingData = async (id: string) => {
  try {
    const bigIntId = BigInt(id);
    const res = await getApplicationFromId(bigIntId) as any;
    if (res.code === 200) {
      // 处理paymentType字段，将逗号分隔的字符串转换为数组
      if (res.data.paymentType) {
        res.data.paymentTypes = res.data.paymentType.split(',').map((item: string) => item.trim());
      } else {
        res.data.paymentTypes = [];
      }
      
      Object.assign(form, res.data);
      totalRecord.value = 1; // 编辑模式
    }
  } catch (error) {
    ElMessage.error('加载数据失败');
  }
};

// 组件挂载时加载数据
onMounted(() => {
  const id = props.id || router.currentRoute.value.query.id;
  if (id) {
    loadExistingData(id.toString());
    totalRecord.value = 1;
  } else {
    totalRecord.value = 0;
    // form.status = 0;
    // 其它字段清空，type字段不清空
    // Object.keys(form).forEach(key => {
    //   if (key !== 'status' && key !== 'type') form[key] = Array.isArray(form[key]) ? [] : '';
    // });
    // 重置为初始状态，使用 reactive 的正确方式
    Object.assign(form, {
      type: 1,
      name: '',
      applyDate: '',
      itemName: '',
      numbers: 0,
      contactName: '',
      contactPhone: '',
      registerDate: '',
      organizationCode: '',
      industry: '',
      otherIndustry: '',
      registerMoney: 0,
      ShareholdingRatio: '',
      isQualified: false,
      businessScope: '',
      members: [
        {
          name: '',
          department: '',
          major: '',
          phone: '',
          qq: '',
          job: '',
        },
      ],
      hasPhysicalSpace: false,
      seatNumber: '',
      paymentTypes: [],
      paymentAmount: 0,
      projectIntroduction: '',
      helpDescription: '',
      teacherOpinion: '',
      collegeOpinion: '',
      officeOpinion: '',
      leaderOpinion: '',
      status: 0,
      id: undefined,
      paymentType: '', // 添加这一行确保字段存在
    });
  }

  // 初始化至少一个成员
  if (form.members.length === 0) {
    form.members.push({
      name: '',
      department: '',
      major: '',
      phone: '',
      qq: '',
      job: '',
    });
  }
});

// 新增文件列表
const certificateList = ref<UploadFile[]>([]);
const projectFileList = ref<UploadFile[]>([]);
const paymentReceiptList = ref<UploadFile[]>([]);

// 通用文件上传方法
const handleFileUpload = async (file: UploadFile, field: 'certificate' | 'paymentReceipt' | 'projectfile') => {
  if (!file.raw) return;
  const isValidFormat = file.raw.type.includes('image/') || file.raw.type === 'application/pdf';
  if (!isValidFormat) {
    ElMessage.error('只能上传jpg/png/pdf格式的文件！');
    if (field === 'certificate') certificateList.value = [];
    if (field === 'projectfile') projectFileList.value = [];
    if (field === 'paymentReceipt') paymentReceiptList.value = [];
    return false;
  }
  const formData = new FormData();
  formData.append('file', file.raw);
  try {
    const res = await uploadFile(formData);
    (form as any)[field] = res.data.url;
    ElMessage.success('上传成功');
    if (field === 'certificate') certificateList.value = [{...file, url: res.data.url}];
    if (field === 'projectfile') projectFileList.value = [{...file, url: res.data.url}];
    if (field === 'paymentReceipt') paymentReceiptList.value = [{...file, url: res.data.url}];
  } catch (error) {
    ElMessage.error('上传失败');
    if (field === 'certificate') certificateList.value = [];
    if (field === 'projectfile') projectFileList.value = [];
    if (field === 'paymentReceipt') paymentReceiptList.value = [];
  }
};

// 处理缴费回单上传
const handleSpaceChange = (value: boolean) => {
  if (!value) {
    form.seatNumber = '';
  }
};

// 监听表单数据变化并保存到 localStorage
watch(
    form,
    (newForm) => {
      localStorage.setItem('ResidencyApplicationTeacherForm', JSON.stringify(newForm));
    },
    { deep: true }
);

// 增加成员
const addMember = () => {
  formRef.value?.clearValidate('members')
  form.members.push({
    name: '',
    department: '',
    major: '',
    phone: '',
    qq: '',
    job: '',
  });
};

// 删除成员
const removeMember = (index: number) => {
  form.members.splice(index, 1);
};

// 格式化日期为YYYY-MM-DD
function formatDateToYMD(dateStr: string): string {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

// 提交表单
const submitForm = async () => {
  formRef.value?.validate(async (valid: any) => {
    if (valid) {
      form.status = 1;
      // 日期格式化
      if (form.applyDate) form.applyDate = formatDateToYMD(form.applyDate);
      if (form.registerDate) form.registerDate = formatDateToYMD(form.registerDate);
      
      // 将paymentTypes数组转换为逗号分隔的字符串
      const submitData = { ...form };
      if (Array.isArray(form.paymentTypes)) {
        submitData.paymentType = form.paymentTypes.join(',');
      } else {
        submitData.paymentType = form.paymentTypes || '';
      }
      
      // 删除paymentTypes字段，避免提交给后端
      delete (submitData as any).paymentTypes;
      
      try {
        const api = totalRecord.value === 1 ? editApplication : zcresidencyApplication;
        const res = await api(submitData as any);
        if (res.code === 200) {
          ElMessage.success(totalRecord.value === 1 ? '更新成功' : '提交成功');
          localStorage.removeItem('ResidencyApplicationTeacherForm');
          router.push('/personal-center/enterprise-settlement/my-application');
        }
      } catch (error) {
        ElMessage.error('提交失败');
      }
    } else {
      ElMessage.error('表单信息有误或未填写完整');
    }
  });
};

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields();
  Object.assign(form, {
    type: 1,
    name: '',
    applyDate: '',
    itemName: '',
    numbers: 0,
    contactName: '',
    contactPhone: '',
    registerDate: '',
    organizationCode: '',
    industry: '',
    otherIndustry: '',
    registerMoney: 0,
    shareholdingRatio: '',
    isQualified: false,
    businessScope: '',
    members: [
      {
        name: '',
        department: '',
        major: '',
        phone: '',
        qq: '',
        job: '',
      },
    ],
    hasPhysicalSpace: false,
    seatNumber: '',
    paymentTypes: [],
    paymentAmount: 0,
    projectIntroduction: '',
    helpDescription: '',
    teacherOpinion: '',
    collegeOpinion: '',
    officeOpinion: '',
    leaderOpinion: '',
    status: 0,
    id: undefined,
  });
  // 重置文件上传
  certificateList.value = [];
  projectFileList.value = [];
  paymentReceiptList.value = [];
  // 清除本地存储
  localStorage.removeItem('ResidencyApplicationTeacherForm');
};

const isSubmit = ref(false);

const saveDraft = async () => {
  try {
    form.status = 0;
    // 日期格式化
    if (form.applyDate) form.applyDate = formatDateToYMD(form.applyDate);
    if (form.registerDate) form.registerDate = formatDateToYMD(form.registerDate);
    
    // 将paymentTypes数组转换为逗号分隔的字符串
    const submitData = { ...form };
    if (Array.isArray(form.paymentTypes)) {
      submitData.paymentType = form.paymentTypes.join(',');
    } else {
      submitData.paymentType = form.paymentTypes || '';
    }
    
    // 删除paymentTypes字段，避免提交给后端
    delete (submitData as any).paymentTypes;
    
    const api = totalRecord.value === 1 ? editApplication : zcresidencyApplication;
    const res = await api(submitData as any);
    if (res.code === 200) {
      ElMessage.success('草稿保存成功');
      localStorage.removeItem('ResidencyApplicationTeacherForm');
      router.push('/personal-center/enterprise-settlement/my-application');
    } else {
      ElMessage.error(res.msg || '保存失败');
    }
  } catch (error) {
    ElMessage.error('保存失败');
  }
};

// 状态标签工具函数
const getStatusType = (status: number) => {
  switch (status) {
    case 0: return 'info';
    case 1: return 'warning';
    case 2: return 'success';
    case 3: return 'danger';
    default: return 'info';
  }
};
const getStatusText = (status: number) => {
  switch (status) {
    case 0: return '草稿';
    case 1: return '已提交';
    case 2: return '审核通过';
    case 3: return '审核失败';
    default: return '未知状态';
  }
};

</script>
<style lang="scss" scoped>
.residency-application {
  width: 100%;
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 4px;

  h1 {
    text-align: center;
    color: #409eff;
    margin-bottom: 10px;
  }

  h2 {
    text-align: center;
    margin-bottom: 30px;
    color: #666;
  }

  .header {
    font-weight: bold;
    font-size: 18px;
    color: #333;
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;
  }

  .header1 {
    font-weight: bold;
    font-size: 20px;
    // margin-bottom: 10px;
  }

  .el-card {
    margin-bottom: 20px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .el-form-item {
    margin-bottom: 22px;
  }

  .el-input-number {
    width: 100%;
  }

  .el-select {
    width: 100%;
  }

  .el-date-editor {
    width: 100%;
  }

  .el-upload__tip {
    font-size: 12px;
    color: #999;
    margin-top: 5px;
  }

  .promise-text {
    font-size: 16px;
    line-height: 1.8;

    .el-input {
      width: 200px;
      margin-left: 10px;
    }

    .el-date-editor {
      width: 200px;
      margin-left: 10px;
    }
  }

  .el-table {
    margin-top: 10px;

    .el-button {
      padding: 5px 10px;
    }

    :deep(.el-form-item) {
      margin-bottom: 0;
    }
    
    :deep(.el-form-item__content) {
      line-height: normal;
    }
    
    :deep(.el-input) {
      vertical-align: top;
    }
  }

  .el-checkbox-group {
    display: flex;
    flex-wrap: wrap;

    .el-checkbox {
      margin-right: 20px;
      margin-bottom: 10px;
    }
  }

  .el-radio-group {
    .el-radio {
      margin-right: 20px;
    }
  }

  > span {
    display: block;
    margin-top: 20px;
    font-size: 14px;
    color: #999;
    text-align: center;
  }
}

@media (max-width: 768px) {
  .residency-application {
    padding: 15px;

    .el-form-item {
      margin-bottom: 18px;
    }

    .el-col {
      margin-bottom: 15px;
    }
  }
}

.status-display {
  margin-bottom: 20px;
  text-align: center;
  .el-tag {
    font-size: 16px;
    padding: 8px 16px;
  }
}
</style>
